import cx_Oracle
import sys


#sys.argv[2]="EX"  exchange;sys.argv[2]="BK" bank;  sys.argv[2]="ALL"
#sys.argv[3]="PRE"  Pre day;sys.argv[3]="NEXT" Next day

if len(sys.argv)<4:
	print "you need to provide one argument to this script!"
#print "bizdate="+sys.argv[1]
else:
	con=cx_Oracle.connect("cdwbase","cdwbase","cdw")

	cursor = con.cursor()

#dir(cursor)
	bindVar={'arg1': sys.argv[1]}
	#print bindVar
#sql="select * from t06_stock where invt_var_id = :cd"
	if sys.argv[2]=="EX" and sys.argv[3]=="PRE" :
		sql="select max(day_dt) from cdwanalyse.t00_day_def where excg_tx_day_ind=0 and day_dt< to_date(:arg1,'yyyy-mm-dd')"
	elif  sys.argv[2]=="EX" and sys.argv[3]=="NEXT" :
		sql="select min(day_dt) from cdwanalyse.t00_day_def where excg_tx_day_ind=0 and day_dt> to_date(:arg1,'yyyy-mm-dd')"
	elif  sys.argv[2]=="BK" and sys.argv[3]=="PRE" :
		sql="select max(day_dt) from cdwanalyse.t00_day_def where outbd_tx_day_ind=0 and day_dt< to_date(:arg1,'yyyy-mm-dd')"
	elif  sys.argv[2]=="BK" and sys.argv[3]=="NEXT" :
		sql="select min(day_dt) from cdwanalyse.t00_day_def where outbd_tx_day_ind=0 and day_dt> to_date(:arg1,'yyyy-mm-dd')"
	elif  sys.argv[2]=="ALL" and sys.argv[3]=="PRE" :
		sql="select max(day_dt) from cdwanalyse.t00_day_def where (excg_tx_day_ind=0 or outbd_tx_day_ind=0) and day_dt< to_date(:arg1,'yyyy-mm-dd')"
	else:
		sql="select min(day_dt) from cdwanalyse.t00_day_def where (excg_tx_day_ind=0 or outbd_tx_day_ind=0) and day_dt> to_date(:arg1,'yyyy-mm-dd')"
#cursor.execute(sql, arg1=stockCD)
	cursor.execute(sql, bindVar)

	row=cursor.fetchall()
	sys.stdout.write(row[0][0].strftime("%Y-%m-%d"))
	#print cursor.rowcount
	cursor.close()

	con.close()

#print "hello world!"
